﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SweetSurvey.Models.Repositories
{
    public class EditorRepository: RepositoryBase, IEditorRepository
    {
        #region IEditorRepository Members

        public string CreateTemporaryEditor()
        {
            return this.Create(new Editor());
        }

        public void CreateIfNotExisted(string editorId)
        {
            var context = new SweetSurveyModelContainer();
            var count = context.Editors.Where(e => e.Id == editorId).Count();
            if (count == 0)
            {
                context.Editors.AddObject(new Editor() { Id = editorId });
                context.SaveChanges();
            }
        }

        #endregion

        #region IRepository<Editor,string> Members

        public Editor Get(string id, bool detaching = true)
        {
            var context = new SweetSurveyModelContainer();
            var entity = context.Editors.Where(e => e.Id == id).Single();
            if (detaching) { context.Detach(entity); }
            return entity;
        }

        public string Create(Editor entity)
        {
            if (string.IsNullOrEmpty(entity.Id))
                entity.Id = RepositoryBase.GenerateRandomId();
            var context = new SweetSurveyModelContainer();
            context.Editors.AddObject(entity);
            context.SaveChanges();
            return entity.Id;
        }

        public void Update(Editor entity)
        {
            RepositoryBase.Update(entity);
        }

        public void Delete(string id)
        {
            RepositoryBase.Delete(Get(id));
        }

        #endregion
    }
}